const url = require('url');
const fs = require('fs');
const path = require('path');
const pkg = require('./package.json');

const gulp = require('gulp');
const less = require('gulp-less');
const gulpif = require('gulp-if');

const header = require('gulp-header');
const uglify = require('gulp-uglify');
const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');

const livereload = require('gulp-livereload');
const webserver = require('gulp-webserver');

const headerTpl = '/** kitadmin-v${version} ${license} License By ${homepage} Author ${author} */\n';
const headerData = pkg;

//web服务器 用于开发环境
gulp.task('webserver', function() {
  gulp.src('./src/') // 服务器目录（./代表根目录）
    .pipe(webserver({ // 运行gulp-webserver
      port: 8000, //端口，默认8000
      livereload: true, // 启用LiveReload
      open: true, // 服务器启动时自动打开网页
      directoryListing: {
        enable: true,
        path: 'index.html' //配置默认访问页面
      },
      middleware: function(req, res, next) {
        //mock local data
        const urlObj = url.parse(req.url, true),
          method = req.method;
        if (!urlObj.pathname.match(/^\/api/)) { //不是api开头的数据，直接next
          next();
          return;
        }
        const mockDataFile = path.join(__dirname, urlObj.pathname) + ".js";
        //file exist or not
        fs.access(mockDataFile, fs.F_OK, function(err) {
          if (err) {
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify({
              "status": "没有找到此文件",
              "notFound": mockDataFile
            }));
            return;
          }
          const data = fs.readFileSync(mockDataFile, 'utf-8');
          res.setHeader('Content-Type', 'application/json');
          res.end(data);
        });
        next();
      },
      proxies: []
    }));
});
// 编译less
gulp.task('less', function() {
  return gulp.src('./src/less/*.less')
    // .pipe(gulpif(['!kitadmin.less', '!menu.less'], less()))  //要过滤的less
    .pipe(less())
    .pipe(gulp.dest('./src/css/'));
});
// 打包js
gulp.task('js', function() {
  return gulp.src(['./src/js/*.js'])
    // .pipe(sourcemaps.init())
    .pipe(babel({
      presets: ['env'],
      plugins: ['transform-es2015-modules-umd']
    }))
    // .pipe(uglify())
    // .pipe(header(headerTpl + ';', headerData))
    // .pipe(sourcemaps.write('.'))
    .pipe(gulp.dest('./src/js/dist'));
});

gulp.task('dev', ['js','less', 'webserver']);

const jsWatcher = gulp.watch('./src/js/*.js', ['js']);
jsWatcher.on('change', function(event) {
  console.log('JS ' + event.path + ' was ' + event.type + ', running tasks.');
});

// 监听less文件的变更进步热编译
const lessWatcher = gulp.watch('./src/less/*.less', ['less']);
lessWatcher.on('change', function(event) {
  console.log('LESS ' + event.path + ' was ' + event.type + ', running tasks.');
});